import { Component, OnInit, OnDestroy } from '@angular/core'
import { FormBuilder, Validators } from '@angular/forms'
import { Subject } from 'rxjs'
import { takeUntil, debounceTime } from 'rxjs/operators'
import { NzMessageService } from 'ng-zorro-antd'

import { I18NService } from '@core'
import { NewPageBaseClass } from '@shared/classes/NewPageBaseClass'
import { TerminalStoreService } from '../terminal-store.service'
import { IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import {
  makeAllControlDirty,
  getAAMSMerchant,
  getAAMSAcquirer,
  getAAMSGroup,
  getAAMSStore,
  acquirerEditPermission,
  agentEditPermission,
  storeEditPermission,
  merchantEditPermission,
} from 'app/utils/helpers'
import { TerminalNewRequest } from '@shared/interfaces/terminal'
import { SettingsService } from '@delon/theme'
import { User } from '@shared/interfaces/user'

@Component({
  selector: 'app-terminal-new-system',
  templateUrl: './system.component.html',
  styleUrls: ['../../../../shared/styles/new-page-form.less'],
})
export class TerminalNewSystemComponent extends NewPageBaseClass implements OnInit, OnDestroy {
  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    private fb: FormBuilder,
    private terminalStore: TerminalStoreService,
    public settings: SettingsService,
  ) {
    super(msg, i18n)
  }

  terminal: TerminalNewRequest

  chosenAcquirer: IAamsItem = {}
  chosenGroup: IAamsItem = {}
  chosenMerchant: IAamsItem = {}
  chosenStore: IAamsItem = {}

  groupRestorer$ = new Subject()
  merchantRestorer$ = new Subject()
  storeRestorer$ = new Subject()
  destroy$ = new Subject()

  ngOnInit() {
    this.terminal = this.terminalStore.value
    this.initValidateForm()
    this.subscribeObservables()
  }

  ngOnDestroy(): void {
    this.destroy$.next()
    this.destroy$.complete()
  }

  initValidateForm(): void {
    const terminal = this.terminalStore.value
    const { selectedStore } = terminal
    const authUser = this.settings.user as User

    if (selectedStore) {
      // 填充信息
      this.chosenAcquirer = {
        num: terminal.insCode,
        code: terminal.insCode,
        name: terminal.insName,
        nameEN: terminal.insNameEN,
      }

      if (terminal.agentCode) {
        this.chosenGroup = {
          num: terminal.agentCode,
          code: terminal.agentCode,
          name: terminal.agentName,
          nameEN: terminal.agentNameEN,
        }
      }
      this.chosenMerchant = {
        num: terminal.merNum,
        code: terminal.intMerCode,
        name: terminal.merName,
        nameEN: terminal.merNameEN,
      }
      this.chosenStore = {
        num: selectedStore.num,
        code: selectedStore.code,
        name: selectedStore.name,
        nameEN: selectedStore.nameEN,
      }
    } else {
      this.chosenAcquirer = getAAMSAcquirer(authUser)
      this.chosenGroup = getAAMSGroup(authUser)
      this.chosenMerchant = getAAMSMerchant(authUser)
      this.chosenStore = getAAMSStore(authUser)
    }
    this.validateForm = this.fb.group({
      // Setup acquirer select field
      acquirer: [
        {
          value: this.chosenAcquirer.code ? this.chosenAcquirer : null,
          disabled: acquirerEditPermission(authUser),
        },
      ],
      acquirerName: [this.chosenAcquirer.name],
      acquirerNameEN: [this.chosenAcquirer.nameEN],
      // Setup group select field
      group: [
        {
          value: this.chosenGroup.code ? this.chosenGroup : null,
          disabled: agentEditPermission(authUser),
        },
      ],
      groupName: [this.chosenGroup.name],
      groupNameEN: [this.chosenGroup.nameEN],
      merchant: [
        {
          value: this.chosenMerchant.code ? this.chosenMerchant : null,
          disabled: merchantEditPermission(authUser),
        },
      ],
      merchantName: [this.chosenMerchant.name],
      merchantNameEN: [this.chosenMerchant.nameEN],
      store: [
        {
          value: this.chosenStore.code ? this.chosenStore : null,
          disabled: storeEditPermission(authUser),
        },
        [Validators.required],
      ],
      storeName: [this.chosenStore.name],
      storeNameEN: [this.chosenStore.nameEN],
    })
  }

  checkValid(): boolean {
    if (this.validateForm.valid) {
      this.pushDataToStore()
      return true
    }

    makeAllControlDirty(this.validateForm)
    this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    return false
  }

  pushDataToStore(): void {
    this.terminal.selectedStore = this.chosenStore
    this.terminal.intStoreCode = this.chosenStore.code

    this.terminal.insCode = this.chosenAcquirer.code
    this.terminal.insName = this.chosenAcquirer.name
    this.terminal.insNameEN = this.chosenAcquirer.nameEN

    this.terminal.agentCode = this.chosenGroup.code
    this.terminal.agentName = this.chosenGroup.name
    this.terminal.agentNameEN = this.chosenGroup.nameEN

    this.terminal.intMerCode = this.chosenMerchant.code
    this.terminal.merNum = this.chosenMerchant.num ? this.chosenMerchant.num : this.chosenMerchant.code
    this.terminal.merName = this.chosenMerchant.name
    this.terminal.merNameEN = this.chosenMerchant.nameEN

    this.terminalStore.setValue(this.terminal)
  }

  /** 选中选项 */
  handleChosenAcquirer(value: IAamsItem): void {
    if (!value) {
      value = {}
    }

    this.chosenAcquirer = value
    this.validateForm.get('acquirerName').setValue(value.name)
    this.validateForm.get('acquirerNameEN').setValue(value.nameEN)

    this.groupRestorer$.next()
    this.merchantRestorer$.next()
    this.storeRestorer$.next()
  }

  handleChosenGroup(value: IAamsItem | null): void {
    if (!value) {
      value = {}
    }

    this.chosenGroup = value
    this.validateForm.get('groupName').setValue(value.name)
    this.validateForm.get('groupNameEN').setValue(value.nameEN)

    this.merchantRestorer$.next()
    this.storeRestorer$.next()
  }

  handleChosenMerchant(value: IAamsItem | null): void {
    if (!value) {
      value = {}
    }

    this.chosenMerchant = value
    this.validateForm.get('merchantName').setValue(value.name)
    this.validateForm.get('merchantNameEN').setValue(value.nameEN)

    this.storeRestorer$.next()
  }

  handleChosenStore(value: IAamsItem | null): void {
    if (!value) {
      value = {}
    }

    this.chosenStore = value
    this.validateForm.get('storeName').setValue(value.name)
    this.validateForm.get('storeNameEN').setValue(value.nameEN)
    this.terminal.intStoreCode = this.chosenStore.code
  }

  private subscribeObservables() {
    this.groupRestorer$
      .asObservable()
      .pipe(
        takeUntil(this.destroy$),
        debounceTime(300),
      )
      .subscribe(() => {
        this.resetGroup()
      })

    this.merchantRestorer$
      .asObservable()
      .pipe(
        takeUntil(this.destroy$),
        debounceTime(300),
      )
      .subscribe(() => {
        this.resetMerchant()
      })

    this.storeRestorer$
      .asObservable()
      .pipe(
        takeUntil(this.destroy$),
        debounceTime(300),
      )
      .subscribe(() => {
        this.resetStore()
      })
  }

  private resetGroup(): void {
    const selectedGroup = this.validateForm.get('group').value
    if (selectedGroup) {
      this.validateForm.get('group').setValue(null)
      this.validateForm.get('groupName').setValue('')
      this.validateForm.get('groupNameEN').setValue('')
    }
  }

  private resetMerchant(): void {
    const selectedMerchant = this.validateForm.get('merchant').value
    if (selectedMerchant) {
      this.validateForm.get('merchant').setValue(null)
      this.validateForm.get('merchantName').setValue('')
      this.validateForm.get('merchantNameEN').setValue('')
    }
  }

  private resetStore(): void {
    const selectedStore = this.validateForm.get('store').value
    if (selectedStore) {
      this.validateForm.get('store').setValue(null)
      this.validateForm.get('storeName').setValue('')
      this.validateForm.get('storeNameEN').setValue('')
    }
  }
}
